<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="播放器标识" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入播放器标识"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="播放器名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入播放器名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="播放器状态" style="width: 150px" clearable>
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['basic:player:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basic:player:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['basic:player:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['basic:player:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="playerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="播放器ID" align="center" prop="playerId" width="100" />
      <el-table-column label="播放器标识" align="center" prop="code" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="播放器名称" align="center" prop="name" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="需要解析" align="center" prop="needParse" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.needParse === '1'" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" width="80" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:player:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['basic:player:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改播放器配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="playerRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="播放器标识" prop="code">
              <el-input v-model="form.code" placeholder="请输入播放器标识(英文,唯一)" :disabled="form.playerId != null" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="播放器名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入播放器名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" :max="9999" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="需要解析" prop="needParse">
              <el-radio-group v-model="form.needParse">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="打开方式" prop="target">
              <el-select v-model="form.target" placeholder="请选择打开方式">
                <el-option label="当前窗口(_self)" value="_self" />
                <el-option label="新窗口(_blank)" value="_blank" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="解析接口地址" prop="parseApi">
          <el-input v-model="form.parseApi" placeholder="请输入解析接口地址(需要解析时填写)" />
        </el-form-item>
        <el-form-item label="播放器描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入播放器描述" />
        </el-form-item>
        <el-form-item label="提示信息" prop="tip">
          <el-input v-model="form.tip" placeholder="请输入提示信息" />
        </el-form-item>
        <el-form-item label="播放器JS代码" prop="playerCode">
          <el-input v-model="form.playerCode" type="textarea" :rows="6" placeholder="请输入播放器JS代码(选填)" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的播放器数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Player">
import { listPlayer, getPlayer, delPlayer, addPlayer, updatePlayer, checkCodeUnique } from "@/api/basic/player";
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';
import { getToken } from "@/utils/auth";
import { UploadFilled } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();

const playerList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const uploadRef = ref();

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: null,
    name: null,
    status: null,
    needParse: null
  },
  rules: {
    code: [
      { required: true, message: "播放器标识不能为空", trigger: "blur" },
      { min: 2, max: 50, message: "播放器标识长度必须介于 2 和 50 之间", trigger: "blur" },
      { pattern: /^[a-z0-9_]+$/, message: "播放器标识只能包含小写字母、数字和下划线", trigger: "blur" }
    ],
    name: [
      { required: true, message: "播放器名称不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ]
  },
  upload: {
    open: false,
    title: "",
    isUploading: false,
    updateSupport: 0,
    headers: { Authorization: "Bearer " + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + "/basic/player/importData"
  }
});

const { queryParams, form, rules, upload } = toRefs(data);

/** 查询播放器配置列表 */
function getList() {
  loading.value = true;
  listPlayer(queryParams.value).then(response => {
    playerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    playerId: null,
    code: null,
    name: null,
    description: null,
    status: "1",
    sort: 100,
    parseApi: null,
    needParse: "0",
    target: "_self",
    tip: null,
    playerCode: null,
    remark: null
  };
  proxy.resetForm("playerRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.playerId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加播放器配置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const playerId = row.playerId || ids.value;
  getPlayer(playerId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改播放器配置";
  });
}

/** 播放器状态修改 */
function handleStatusChange(row) {
  let text = row.status === "1" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.name + '"播放器吗？').then(() => {
    return updatePlayer(row);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(() => {
    row.status = row.status === "1" ? "0" : "1";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["playerRef"].validate(valid => {
    if (valid) {
      // 校验播放器标识唯一性
      checkCodeUnique(form.value).then(response => {
        if (response === "1") {
          proxy.$modal.msgError("播放器标识已存在");
          return;
        }

        if (form.value.playerId != null) {
          updatePlayer(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addPlayer(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const playerIds = row.playerId || ids.value;
  proxy.$modal.confirm('是否确认删除播放器配置编号为"' + playerIds + '"的数据项？').then(() => {
    return delPlayer(playerIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('basic/player/export', {
    ...queryParams.value
  }, `player_${new Date().getTime()}.xlsx`);
}

/** 导入按钮操作 */
function handleImport() {
  upload.value.title = "播放器配置导入";
  upload.value.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download('basic/player/importTemplate', {
  }, `player_template_${new Date().getTime()}.xlsx`);
}

/** 文件上传中处理 */
function handleFileUploadProgress(event, file, fileList) {
  upload.value.isUploading = true;
}

/** 文件上传成功处理 */
function handleFileSuccess(response, file, fileList) {
  upload.value.open = false;
  upload.value.isUploading = false;
  uploadRef.value.clearFiles();
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
}

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value.submit();
}

getList();
</script>
